#include "stdafx.h"
#include "Console.h"
#include "LPWorkThread.h"

int APIENTRY _tWinMain(HINSTANCE hInstance,
					   HINSTANCE hPrevInstance,
					   LPTSTR    lpCmdLine,
					   int       nCmdShow)
{
	console::init();

	CWSAAutoStartUp wsasu;	

	CSocket sockListen;
	if(!sockListen.Create(AF_INET,SOCK_STREAM,IPPROTO_TCP))
	{
		console::_tprintf(_T("Socket Init Error %d\n"),WSAGetLastError());
		return -1;
	}

	{
		sockaddr_in addr={0};
		addr.sin_family=AF_INET;
		addr.sin_port=htons(8000);
		addr.sin_addr.s_addr=inet_addr("0.0.0.0");
		
		if(!sockListen.Bind(&addr,sizeof(struct sockaddr_in)))
		{
			console::_tprintf(_T("Socket Bind Error %d\n"),WSAGetLastError());
			return -1;
		}
		
		if(!sockListen.Listen(SOMAXCONN))
		{
			console::_tprintf(_T("Socket Listen Error %d\n"),WSAGetLastError());
			return -1;
		}
	}

	while(1)
	{		
		sockaddr_in addrRemote;
		int addrLen=sizeof(sockaddr_in);
		SOCKET sockRemote=sockListen.Accept(&addrRemote,&addrLen);
		if(sockRemote==INVALID_SOCKET)
		{
			console::_tprintf(_T("Socket Accept Error %d\n"),WSAGetLastError());
			return -1;
		}
		CProxyThread::NewWorkThread(sockRemote,addrRemote);
	}

	return 0;
}
